package com.dingyh.shopwebbackground.controller;


import com.alibaba.fastjson.JSONArray;
import com.dingyh.shopwebbackground.entity.*;
import com.dingyh.shopwebbackground.service.*;
import com.dingyh.shopwebbackground.util.CommonResult;
import com.dingyh.shopwebbackground.util.UUIDUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dingyuhan
 * @since 2023-02-17
 */
@RestController
@CrossOrigin
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    OrdersService ordersService;

    @Autowired
    private ShopCarService shopCarService;

    @Autowired
    private CommodityService commodityService;

    @Autowired
    private BusinessService businessService;

    @Autowired
    private UserService userService;

    @Autowired
    private PayoutsService payoutsService;

    /**
     * 买家获取订单表
     * @param menuKey
     * @param userId
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @RequestMapping("/getOrderList")
    public CommonResult<Object> getOrderList(String menuKey,String userId, @RequestParam(defaultValue = "1",required = true )int pageIndex, @RequestParam(defaultValue = "10",required = true )int pageSize){
        PageHelper.offsetPage((pageIndex - 1) * pageSize,pageSize);
        if ( menuKey.equals("0") ) {
            List<Orders> ordersList = ordersService.getAllList(userId);
            PageInfo<Orders> pageInfo = new PageInfo<>(ordersList);
            return new CommonResult(200,"",pageInfo);
        } else if ( menuKey.equals("2") ) {
            List<Orders> ordersList = ordersService.getOrderListTwo();
            PageInfo<Orders> pageInfo = new PageInfo<>(ordersList);
            return new CommonResult(200,"",pageInfo);
        }
        else {
            Map<String, Object> map = new HashMap<>();
            if (menuKey.equals( "1" )){
                map.put("state",menuKey);
            }else {
                map.put("state","4");
            }
            List<Orders> ordersList = ordersService.getOrderList(map);
            PageInfo<Orders> pageInfo = new PageInfo<>(ordersList);
            return new CommonResult(200,"",pageInfo);}
    }

    /**
     * 商家获取订单表
     * @param companyId
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @RequestMapping("/getBySaleId")
    public CommonResult<Object> getBySaleId(String companyId,@RequestParam(defaultValue = "1",required = true )int pageIndex, @RequestParam(defaultValue = "10",required = true )int pageSize){
        PageHelper.offsetPage((pageIndex-1)*pageSize,pageSize);
        List<Orders> ordersList = ordersService.getSaleList(companyId);
        ordersList.forEach(orders -> {
            if (orders.getState().equals("1")){
                orders.setSaleState("0");
            }else if (orders.getState().equals("2")){
                orders.setSaleState("6");
            }else if(orders.getState().equals("5")){
                orders.setSaleState("2");
            }else if(orders.getState().equals("9")){
                orders.setSaleState("3");
            }else if(orders.getState().equals("10")){
                orders.setSaleState("4");
            }else {
                orders.setSaleState("1");
            }
        });
        PageInfo<Orders> pageInfo = new PageInfo<>(ordersList);
        return new CommonResult(200,"",pageInfo);
    };

    /**
     * id查找order表
     * @param id
     * @return
     */
    @RequestMapping("/selectOrder")
    public CommonResult selectOrder(String id){
        Map<String,Object> map = new HashMap<>();
        map.put("id",id);
        Orders orders = ordersService.selectOrder(map);
        if(orders != null){
            return new CommonResult(200,"",orders);
        }else{
            return new CommonResult(500,"您查找的订单不存在！",null);
        }
    }

    /**
     * 更新订单状态（物流等）
     * @param orders
     * @return
     */
    @RequestMapping("/updState")
    public CommonResult<Object> updState(Orders orders){
        if (orders.getState().equals("4")){
            Payouts payouts = payoutsService.getById(orders.getPayId());
            payouts.setState("1-2");
            Orders current = ordersService.getById(orders.getId());
            payouts.setTimearrival(System.currentTimeMillis());
            payoutsService.updateById(payouts);
            User manage = userService.getById("3");
            User sale = userService.getById(current.getCompanyid());
            manage.setMoney(manage.getMoney().subtract(payouts.getMoney()));
            sale.setMoney(sale.getMoney().add(payouts.getMoney()));
            userService.updateById(manage);
            userService.updateById(sale);
        }
        if(ordersService.updState( orders ) ){
            return new CommonResult(200, "修改成功！", null);
        }else{
            return new CommonResult(500, "修改失败！", null);
        }
    }

    /**
     * 删除订单
     * @param id
     * @return
     */
    @RequestMapping("/removeOrder")
    public CommonResult<Object> removeOrder(String id){
        if(ordersService.removeOrder(id)){
            return new CommonResult<>(200,"删除成功！",null);
        }else {
            return new CommonResult<>(500,"删除失败！",null);
        }
    }


    /**
     * 商家首页获取订单数据
     * @return
     */
    @RequestMapping("/getOrderCount")
    public CommonResult<Object> getOrderCount(String userId){
        Integer orderCount  = ordersService.getOrderCount(userId);
        Integer notOrderCount = ordersService.getNotOrderCount(userId);
        return new CommonResult(200, "获取数据成功！", new Integer[]{orderCount, notOrderCount});

    }

    /**
     * 商家首页柱状图
     * @param start
     * @param end
     * @return
     */
    @RequestMapping("/getBar")
    public CommonResult<Object> getBar(Long start, Long end,String userId){
        return new CommonResult<>(200,"",ordersService.getBar(start, end, userId));
    }

    /**
     * 购物车购买
     * @param shopCars
     * @return
     */
    @RequestMapping("/createOrder")
    public CommonResult<Object> createOrder(@RequestParam String shopCars){
        boolean result = true;
        //将String字符串转为List
        List<ShopCar> shopCarList = JSONArray.parseArray(shopCars,ShopCar.class);
        Long time = System.currentTimeMillis();
        for (ShopCar shopCar : shopCarList) {
            String pay = UUIDUtil.generator();
            Commodity commodity = commodityService.selectGoods(shopCar.getCommodityId());
            Orders ordersCurr = Orders.builder()
                    .id(UUIDUtil.generator())
                    .timeadd(time)
                    .goodsid(commodity.getId())
                    .companyid(commodity.getCompanyid())
                    .userid(shopCar.getUserId())
                    .username(shopCar.getUserName())
                    .price(commodity.getPrice())
                    .qty(shopCar.getQty())
                    .amount(shopCar.getQty().multiply(commodity.getPrice()))
                    .useraddress(shopCar.getUseraddress())
                    .state("1")
                    .goodsname(commodity.getTitle())
                    .payId(pay)
                    .build();
            Payouts payouts = Payouts.builder()
                    .id(pay)
                    .source("1")
                    .money(shopCar.getQty().multiply(commodity.getPrice()))
                    .timeadd(time)
                    .state("1-1")
                    .timearrival(0L)
                    .build();
            payoutsService.save(payouts);
            shopCarService.removeWillBuy(shopCar.getId());
            User user = userService.getById(shopCar.getUserId());
            BigDecimal currMoney = user.getMoney().subtract(commodity.getPrice().multiply(shopCar.getQty()));
            user.setMoney(currMoney);
            userService.updBuy(user);
            User manegeUser = userService.getById("3");
            manegeUser.setMoney(manegeUser.getMoney().add(shopCar.getQty().multiply(commodity.getPrice())));
            userService.updateById(manegeUser);
            commodityService.updMonth(shopCar.getCommodityId(),commodity.getMonth().add(shopCar.getQty()));
            if (!(ordersService.save(ordersCurr))) {
                result = false;
            }
        }
        if (result) {
            return new CommonResult(200, "支付成功！", null);
        } else {
            return new CommonResult(500, "支付失败！", null);
        }
    }

    /**
     * 直接购买
     * @param orders
     * @return
     */
    @RequestMapping("/goBuy")
    public CommonResult<Object> goBuy(Orders orders){
        Commodity commodity = commodityService.selectGoods(orders.getGoodsid());
        String pay = UUIDUtil.generator();
        if (commodity.getStock().compareTo(orders.getQty()) > -1){
            Orders ordersCurr = Orders.builder()
                    .id(UUIDUtil.generator())
                    .timeadd(System.currentTimeMillis())
                    .goodsid(orders.getGoodsid())
                    .companyid(commodity.getCompanyid())
                    .userid(orders.getUserid())
                    .username(orders.getUsername())
                    .price(commodity.getPrice())
                    .qty(orders.getQty())
                    .amount(orders.getQty().multiply(commodity.getPrice()))
                    .useraddress(orders.getUseraddress())
                    .state("1")
                    .payId(pay)
                    .goodsname(commodity.getTitle())
                    .build();
            Payouts payouts = Payouts.builder()
                    .id(pay)
                    .source("1")
                    .money(orders.getQty().multiply(commodity.getPrice()))
                    .timeadd(System.currentTimeMillis())
                    .state("1-1")
                    .build();
            payoutsService.save(payouts);
            commodity.setStock(commodity.getStock().subtract( orders.getQty()) );
            commodityService.updStock(commodity);
            User user = userService.getById(orders.getUserid());
            user.setMoney(user.getMoney().subtract(commodity.getPrice().multiply(orders.getQty())));
            userService.updBuy(user);
            User manegeUser = userService.getById("3");
            manegeUser.setMoney(manegeUser.getMoney().add(orders.getQty().multiply(commodity.getPrice())));
            userService.updateById(manegeUser);
            boolean result = ordersService.save(ordersCurr);
            commodityService.updMonth(orders.getGoodsid(),commodity.getMonth().add(orders.getQty()));
            if (result) {
                return new CommonResult(200, "支付成功！", null);
            } else {
                return new CommonResult(500, "支付失败！", null);
            }
        }else {
            return new CommonResult(200, "该商品库存不足，购买失败！", "1");
        }
    }

    /**
     * 商家确认退货签收
     * @param id
     * @return
     */
    @RequestMapping("/finishReturn")
    public CommonResult<Object> finishReturn(String id){
        if(ordersService.finishReturn(id)){
            return new CommonResult(200, "修改成功！", null);
        }else{
            return new CommonResult(500, "修改失败！", null);
        }
    }
}

